package com.huilian.security.app.jwt;



import com.huilian.security.core.properties.SecurityProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;


/**
 * @author: 少凡
 * @Date 2018/3/17 20:52
 */
@Service
@Slf4j
public class JwtTokenServiceImpl implements JwtTokenService {

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public String getUserId(HttpServletRequest request) {
        String token = StringUtils.substringAfter(request.getHeader("Authorization"), "bearer ");

        Claims claims = null;
        try {
            claims = Jwts.parser().setSigningKey(securityProperties.getOauth2().getJwtSigningKey().getBytes("UTF-8"))
                    .parseClaimsJws(token).getBody();
        } catch (UnsupportedEncodingException e) {
            log.error("JwtToken解析UserId失败", e);
            e.printStackTrace();
        }

        return (String) claims.get("user_name");
    }
}
